package com.sxbdjw.situation.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.sxbdjw.situation.R;
import com.sxbdjw.situation.bdjw.RestApi;
import com.sxbdjw.situation.bdjw.webrtc.MqttMessageChannelConfig;
import com.sxbdjw.situation.bdjw.webrtc.WebRTCUtilYP;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.webrtc.EglBase;
import org.webrtc.RendererCommon;
import org.webrtc.SurfaceViewRenderer;

import java.util.List;
import java.util.Set;


public class RtcActivity extends Activity {

    private String[] permissionArray = {Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};

    private final String TAG = "RtcActivity";
    private EglBase mEglBase = EglBase.create();
    private WebRTCUtilYP webRtcUtil1 = null;
    private SurfaceViewRenderer surfaceViewRendererPush = null;

    private WebRTCUtilYP webRtcUtil2 = null;
    private SurfaceViewRenderer surfaceViewRendererPlay = null;

    private ImageView acceptButton;
    private ImageView ringHangoff;
    private MediaPlayer mMediaPlayer;

    private TextView textUsername;
    private TextView textInvite;

    private LinearLayout acceptView;
    private LinearLayout runningBtnView;

    private ImageView runningSwitchCarema;
    private ImageView runningHangOff;
    private ImageView runningSwitchSound;

    private TextView outPutText;

    // 是否外放
    private boolean isOutput = false;

    private AudioManager audioManager;

    String myId;
    String myName;

    String playUserId;
    String roomId;
    String webRtcUserIdUrl;

    private MqttClient client;


    public static void startAct(Context context, JSONObject object) {
        Intent intent = new Intent(context, RtcActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("roomId", object.getString("roomId"));
        intent.putExtra("userName", object.getString("userName"));
        intent.putExtra("ownUrl", object.getString("ownUrl"));
        intent.putExtra("event", object.getString("event"));
        intent.putExtra("type", object.getString("type"));
        intent.putExtra("userId", object.getString("userId"));
        intent.putExtra("myId", object.getString("myId"));
        intent.putExtra("myName", object.getString("myName"));

        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rtc);
//        {"ownUrl":"16992625052461097481709687248576","event":"invite_to_room","userName":"陈坤","type":"video","userId":"1699262505246109748","roomId":"1765182420267749422"}
        // 参数获取  start
        Intent in = getIntent();

        // 便利所有参数
        // 获取所有的参数
        Bundle extras = in.getExtras();
        if (extras != null) {
            Set<String> keys = extras.keySet();

            for (String key : keys) {
                String value = extras.getString(key);

                Log.d(TAG, "Parameter Name: " + key);
                Log.d(TAG, "Parameter Value: " + value);
            }
        } else {
            System.out.println("No parameters found.");
        }

        roomId = in.getStringExtra("roomId");
        // 邀请人信息
        playUserId = in.getStringExtra("userId");
        String userName = in.getStringExtra("userName");
        webRtcUserIdUrl = in.getStringExtra("ownUrl");
        // 自己的id
        myId = in.getStringExtra("myId");
        myName = in.getStringExtra("myName");
        // 参数获取  end


        Log.e(TAG, "myId:" + myId);
        Log.e(TAG, "myName:" + myName);
        Log.e(TAG, "ownUrl:" + webRtcUserIdUrl);

        // 声音外放
        audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        outPutText = findViewById(R.id.outPutText);


        String clientId = myId + "_android_rtc";
        try {
            Log.i(TAG, "clientId:" + clientId);
            client = new MqttClient(MqttMessageChannelConfig.broker, clientId,null);

            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(clientId);
            connOpts.setPassword(clientId.toCharArray());
            // 保留会话
            connOpts.setCleanSession(true);

            // 建立连接
            Log.i(TAG, "链接到mqtt服务: " + MqttMessageChannelConfig.broker);
            client.connect(connOpts);

            Log.i(TAG, "链接到mqtt服务 - 链接成功");


            client.subscribe(MqttMessageChannelConfig.userTopic + clientId);

            // 设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {

                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {

                    Log.i(TAG, "接收消息主题:" + topic);
                    Log.i(TAG, "接收消息Qos:" + message.getQos());
                    Log.i(TAG, "接收消息内容:" + new String(message.getPayload()));

                    try {
                        listenMeetingEvent(new String(message.getPayload()));
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {

                }
            });


        } catch (MqttException me) {
            Log.w(TAG, "reason " + me.getReasonCode());
            Log.w(TAG, "msg " + me.getMessage());
            Log.w(TAG, "loc " + me.getLocalizedMessage());
            Log.w(TAG, "cause " + me.getCause());
            Log.w(TAG, "excep " + me);
            me.printStackTrace();
        }


        // 播放声音
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer = MediaPlayer.create(this, R.raw.call);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setLooping(true);
        mMediaPlayer.start();


        surfaceViewRendererPush = findViewById(R.id.localRender);

        surfaceViewRendererPush.init(mEglBase.getEglBaseContext(), null);
        surfaceViewRendererPush.setMirror(false); // 是否设置镜像
        surfaceViewRendererPush.setZOrderMediaOverlay(true); // 是否置于顶层
        // 设置缩放类型，SCALE_ASPECT_FILL表示充满视图
        surfaceViewRendererPush.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
        surfaceViewRendererPush.setEnableHardwareScaler(false); // 是否开启硬件缩放


        surfaceViewRendererPlay = findViewById(R.id.remoteRender);

        surfaceViewRendererPlay.init(mEglBase.getEglBaseContext(), null);
        surfaceViewRendererPlay.setMirror(true); // 是否设置镜像
        surfaceViewRendererPlay.setZOrderMediaOverlay(false); // 是否置于顶层
        // 设置缩放类型，SCALE_ASPECT_FILL表示充满视图
        surfaceViewRendererPlay.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
        surfaceViewRendererPlay.setEnableHardwareScaler(false); // 是否开启硬件缩放

        acceptButton = findViewById(R.id.ring_pickup);
        ringHangoff = findViewById(R.id.ring_hangoff);

        webRtcUtil1 = new WebRTCUtilYP(RtcActivity.this);
        webRtcUtil2 = new WebRTCUtilYP(RtcActivity.this);


        textUsername = findViewById(R.id.textUserName);
        textUsername.setText(userName);

        textInvite = findViewById(R.id.textInvite);
        acceptView = findViewById(R.id.acceptView);
        runningBtnView = findViewById(R.id.runningBtnView);

        runningSwitchCarema = findViewById(R.id.runningSwitchCarema);
        runningHangOff = findViewById(R.id.runningHangOff);
        runningSwitchSound = findViewById(R.id.runningSwitchSound);

        // 切换前后摄像头
        runningSwitchCarema.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webRtcUtil1.changeVideoCapturer();
            }
        });

        // 接听后挂断
        runningHangOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new RestApi().outRoom(myId, roomId, myName);
                finish();
            }
        });
        // 声音外放
        runningSwitchSound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isOutput) {
                    outPutText.setText("听筒播放");
                    // 切换手机听筒
                    audioManager.setMode(AudioManager.MODE_NORMAL);
                    audioManager.setSpeakerphoneOn(false);
                } else {
                    outPutText.setText("扬声器播放");
                    // 切换扬声器
                    audioManager.setMode(AudioManager.MODE_NORMAL);
                    audioManager.setSpeakerphoneOn(true);
                }
                isOutput = !isOutput;

            }
        });

        // 接受视频
        acceptButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                new RestApi().sendInRoom(myId, roomId, myName, "video");

                try {
                    MqttMessage mqttMessage = new MqttMessage();
                    String data = new com.alibaba.fastjson.JSONObject() {{
                        put("event", "in_room");
                        put("type", "video");
                        put("userName", myName);
                        put("userId", myId);
                        put("roomId", roomId);
                    }}.toJSONString();
                    mqttMessage.setPayload(data.getBytes());
                    client.publish("bdjw-user-topic-" + playUserId + "_web", mqttMessage);
                } catch (Exception e) {
                    Log.d(TAG, "发布失败");
                }

                mMediaPlayer.stop();
                textUsername.setVisibility(View.GONE);
                textInvite.setVisibility(View.GONE);
                acceptView.setVisibility(View.GONE);
                runningBtnView.setVisibility(View.VISIBLE);
                // 推送自己
                doPush();
                // 播放别人
                doPlay();
            }
        });

        // 未接听就挂断
        ringHangoff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new RestApi().refuse(myId, roomId, myName);


                finish();
            }
        });
    }


    /**
     * @param eventJson
     * @TODO 监听事件
     */
    private void listenMeetingEvent(String eventJson) throws JSONException {
        JSONObject jsonObject = JSONObject.parseObject(eventJson);

        Log.e(TAG, eventJson);

        String event = jsonObject.getString("event");
        switch (event) {
            case "muted":
                String flag = jsonObject.getString("flag");
                if ("true".equals(flag)) {
                    // 设备禁音
                    audioManager.setMicrophoneMute(true);
                } else {
                    audioManager.setMicrophoneMute(false);
                }

                Log.e(TAG, "isMicrophoneMute:" + audioManager.isMicrophoneMute());
                break;
            case "rotateVideo":
                webRtcUtil1.changeVideoCapturer();
                break;
            case "kickOut":
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMediaPlayer.stop();
        webRtcUtil1.destroy();
        webRtcUtil2.destroy();

        try {
            client.disconnect();
            client.close();
        } catch (Exception e) {

        }


    }

    /**
     * 开始推流
     */
    private void doPush() {

        if (webRtcUtil1 != null) {
            webRtcUtil1.destroy();
        }
        webRtcUtil1 = new WebRTCUtilYP(this);
        webRtcUtil1.create(mEglBase, surfaceViewRendererPush, true, true, myId);
    }

    /**
     * 开始播放
     */
    private void doPlay() {
        if (webRtcUtil2 != null) {
            webRtcUtil2.destroy();
        }
        webRtcUtil2 = new WebRTCUtilYP(this);
        webRtcUtil2.create(mEglBase, surfaceViewRendererPlay, false, true, webRtcUserIdUrl);
    }


}